﻿using System;
using System.Collections.Generic;

namespace Librarinth
{
	public class Locker<N,T> where N : IEquatable<N>
	{
		public IEnumerable<int> AllIndex { get { return nameIndex.Values; } }
		public T[] Datas { get { return DataPool<T>.Datas; } }

		readonly Dictionary<N,int> nameIndex	= new Dictionary<N,int>();

		protected virtual void OnResize(int newSize) { }

		N[] names;
		public N this[int index]
		{ get { return names[index]; } }
		public void GetIndex(N name,out int index)
		{
			if(nameIndex.TryGetValue(name,out index))
			{
				if(!name.Equals(names[index]))
					throw new Exception("Wrong name");
				return;
			}

			DataPool<T>.Alloc(out index);
			if(names == null || names.Length != Datas.Length)
				Array.Resize(ref names,Datas.Length);

			nameIndex.Add(name,index);
			names[index]	= name;
		}
		public void FreeIndex(N name)
		{
			int index;
			if(nameIndex.TryGetValue(name,out index))
			{
				nameIndex.Remove(name);
				names[index]	= default(N);
				DataPool<T>.Free(ref index);
			}
			else throw new Exception("Try free non registered index");
		}
	}
}
